package com.auxgroup.smarthome.repo;

import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.utils.common.LOG;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fju on 2017/8/28.
 * kevin chen 修改 这里一定要是抽象类
 * 只限于获取redis缓存
 */
public abstract class BaseRepo {

    @Autowired
    protected ObjectRedis objectRedis;

    /**
     * redis 中 key的前缀字符串
     */
    protected String pattern="";
    /**
     * 任务分配数量
     */
    protected int shardingCount;

    public BaseRepo() {}

    public BaseRepo(String pattern, int shardingCount) {
        this.pattern = pattern;
        this.shardingCount = shardingCount;
    }


    /**
     * shardingItem 分片号一般不会大的很离谱，
     * 故平分后的余数，直接放进最后一个集合里面即可。
     * 对缓存数据进行分片处理
     * @param shardingItem
     * @return
     */
    public <T> List<T>  getPartDataList(int shardingItem,Class<T> entityClass){
        List<T> allObjects = objectRedis.getAllObjects(pattern, entityClass);
        if (allObjects== null || allObjects.size()==0){
            return new ArrayList<>();
        }
        List<T> newList = new ArrayList<>();
        int partLen = allObjects.size() / shardingCount;
        // 如数据量小于shardingCount分片数量则分配到 0分片号机器处理数据，否则平均分配数据量
        if (partLen==0){
            if(shardingItem == 0){
                newList = allObjects;
            }
        }else{
            // 分配规则：例如[1-10] 分3片，则1[1,2,3], 2[3,4,5], 3[6,7,8,9,10]
            newList = (shardingItem == shardingCount-1) ? allObjects.subList( partLen * shardingItem, allObjects.size())
                    : allObjects.subList( partLen * shardingItem, partLen * (shardingItem+1));
        }
        LOG.info(this,"parLen:"+partLen+
                ",shardingItem:"+shardingItem+
                ",ObjectSize:"+allObjects.size()+"--newList:"+newList.size());
        return newList;
    }
}
